<template>
  <div class="dashboard">
    <h2 class="page-title">Dashboard</h2>
    
    <!-- Statistics Cards -->
    <el-row :gutter="20" class="stat-cards">
      <el-col :span="6" v-for="stat in statistics" :key="stat.title">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: stat.color }">
              <el-icon :size="32">
                <component :is="stat.icon" />
              </el-icon>
            </div>
            <div class="stat-text">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-label">{{ stat.title }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Charts Area -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>Monthly Order Trend</span>
          </template>
          <div ref="orderChartRef" style="height: 300px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>Blood Type Distribution</span>
          </template>
          <div ref="bloodTypeChartRef" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Recent Orders -->
    <el-card class="recent-orders">
      <template #header>
        <div class="card-header">
          <span>Recent Orders</span>
          <el-button type="primary" link @click="$router.push('/orders')">
            View More
          </el-button>
        </div>
      </template>
      <el-table :data="recentOrders" style="width: 100%">
        <el-table-column prop="order_id" label="Order ID" width="100" />
        <el-table-column prop="recipient_name" label="Recipient" />
        <el-table-column prop="donor_code" label="Donor Code" />
        <el-table-column prop="order_date" label="Order Date" />
        <el-table-column prop="total_price" label="Amount">
          <template #default="{ row }">
            ${{ row.total_price }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="Status">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import { statisticsAPI, orderAPI } from '@/api'

const orderChartRef = ref(null)
const bloodTypeChartRef = ref(null)

const statistics = ref([
  { title: 'Active Donors', value: '0', icon: 'User', color: '#409EFF' },
  { title: 'Available Vials', value: '0', icon: 'Box', color: '#67C23A' },
  { title: 'Monthly Orders', value: '0', icon: 'ShoppingCart', color: '#E6A23C' },
  { title: 'Monthly Revenue', value: '$0', icon: 'Money', color: '#F56C6C' }
])

const recentOrders = ref([])

onMounted(async () => {
  await loadDashboardData()
  initCharts()
})

// Load dashboard data
const loadDashboardData = async () => {
  try {
    // Get statistics data
    const res = await statisticsAPI.getDashboard()
    const dashboardData = res.data || {}
    statistics.value[0].value = dashboardData.active_donors || 0
    statistics.value[1].value = dashboardData.available_vials || 0
    statistics.value[2].value = dashboardData.monthly_orders || 0
    statistics.value[3].value = `$${(dashboardData.monthly_revenue || 0).toLocaleString()}`

    // Get recent orders
    const ordersRes = await orderAPI.getList({ page: 1, pageSize: 5 })
    recentOrders.value = ordersRes.data || []
  } catch (error) {
    console.error('Failed to load data:', error)
  }
}

// Initialize charts
const initCharts = async () => {
  try {
    // Order trend chart
    const orderTrendRes = await statisticsAPI.getOrderTrend()
    const orderTrendData = orderTrendRes.data || {}
    const orderChart = echarts.init(orderChartRef.value)
    orderChart.setOption({
      tooltip: { trigger: 'axis' },
      xAxis: {
        type: 'category',
        data: orderTrendData.months || ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
      },
      yAxis: { type: 'value' },
      series: [{
        data: orderTrendData.counts || [10, 15, 20, 18, 25, 30],
        type: 'line',
        smooth: true,
        areaStyle: { color: 'rgba(64, 158, 255, 0.2)' },
        itemStyle: { color: '#409EFF' }
      }]
    })

    // Blood type distribution pie chart
    const bloodTypeRes = await statisticsAPI.getBloodTypeDistribution()
    const bloodTypeData = bloodTypeRes.data || [
      { value: 30, name: 'Type A' },
      { value: 25, name: 'Type B' },
      { value: 20, name: 'Type AB' },
      { value: 25, name: 'Type O' }
    ]
    const bloodTypeChart = echarts.init(bloodTypeChartRef.value)
    bloodTypeChart.setOption({
      tooltip: { trigger: 'item' },
      legend: { orient: 'vertical', left: 'left' },
      series: [{
        type: 'pie',
        radius: '70%',
        data: bloodTypeData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    })
  } catch (error) {
    console.error('Failed to initialize charts:', error)
  }
}

const getStatusType = (status) => {
  const typeMap = {
    'Pending': 'info',
    'Paid': 'warning',
    'Shipped': 'primary',
    'Completed': 'success'
  }
  return typeMap[status] || 'info'
}
</script>

<style scoped>
.dashboard {
  padding: 0;
}

.page-title {
  font-size: 24px;
  font-weight: 500;
  margin-bottom: 20px;
  color: #303133;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: transform 0.2s;
}

.stat-card:hover {
  transform: translateY(-4px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-icon {
  width: 64px;
  height: 64px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.stat-text {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.chart-row {
  margin-bottom: 20px;
}

.recent-orders {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

